package com.travel.server.manager.impl.command.project;

import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dto.request.project.QueryProjectDetailInfoRequest;
import com.travel.server.manager.dto.response.project.QueryProjectDetailInfoResponse;
import com.travel.server.manager.dto.response.project.QueryProjectDetailInfoResponse.ArrangeItem;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.ProjectDal;
import com.travel.server.manager.impl.dal.SpecialDal;
import com.travel.server.manager.impl.dal.SpecialDal.SpecialParam;
import com.travel.server.manager.model.ProjectInfo;
import com.travel.server.manager.model.ProjectSpecial;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Author: LiZhenhui
 * @Date: 2018/10/31 16:48
 * @Desc:
 */
@Component
@Slf4j
public class QueryProjectDetailInfoCommand extends AbstractCommand<QueryProjectDetailInfoRequest, QueryProjectDetailInfoResponse> {

    @Autowired
    private ProjectDal projectDal;

    @Autowired
    private SpecialDal specialDal;

    @Override
    protected void checkInput(QueryProjectDetailInfoRequest request) {
        if(request.getId() == null){
            throwInvalidParam();
        }
    }

    @Override
    public QueryProjectDetailInfoResponse handle(QueryProjectDetailInfoRequest request) {
        checkInput(request);

        ProjectInfo projectInfo = projectDal.selectById(request.getId());
        if(projectInfo == null){
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }

        //查询项目安排
        List<Integer> projectIdList = new ArrayList<>(Arrays.asList(projectInfo.getId()));
        SpecialParam specialParam = new SpecialParam();
        specialParam.setProjectIdList(projectIdList);
        List<ProjectSpecial> specialList = specialDal.selectByExample(specialParam);

        QueryProjectDetailInfoResponse response = new QueryProjectDetailInfoResponse();
        List<ArrangeItem> arrangeList = new ArrayList<>();
        if(!CollectionUtil.isEmpty(specialList)){
            Set<String> daysSet = new HashSet<>();
            for(ProjectSpecial special : specialList){
                if(daysSet.add(special.getDays())) {
                    ArrangeItem item = new ArrangeItem();
                    item.setArrangeId(special.getId());
                    item.setDays(special.getDays());
                    item.setExplains(special.getArrangeExplains());
                    arrangeList.add(item);
                }
            }
        }
        response.setBackground(projectInfo.getBackground());
        response.setArrangeList(arrangeList);
        return response;
    }
}
